package main

import (
	"bufio"
	"fmt"
	"io"
	"net/http"
)

func readBody(response *http.Response) []byte {
	reader := bufio.NewReader(response.Body)
	var res []byte
	for {
		temp := make([]byte, 100)
		_, err := reader.Read(temp)
		if err == io.EOF {
			break
		}
		res = append(res, temp...)
	}
	return res
}

func get() {
	response, err := http.Get("http://httpbin.org/get")
	if err != nil {
		fmt.Printf("请求，err-->%v", err)
		return
	}
	defer response.Body.Close()
	//读取响应体的body
	res := readBody(response)
	fmt.Println(string(res))

	fmt.Println(response.StatusCode)                 //200
	fmt.Println(response.Status)                     //200 OK
	fmt.Println(response.Header.Get("Content-Type")) //application/json

}
func post() {
	response, err := http.Post("http://httpbin.org/post", "", nil)
	if err != nil {
		fmt.Printf("请求，err-->%v", err)
		return
	}
	defer response.Body.Close()
	//读取响应体的body
	res := readBody(response)
	fmt.Println(string(res))
}
func put() {
	//Go语言未提供http.Put方法。所有需要稍微繁琐点，自己实现。查看http.Post的源码发现其底层也是先创建一个request，然后使用DefaultClient的Do方法发起请求的
	request, err := http.NewRequest(http.MethodPut, "http://httpbin.org/put", nil)
	if err != nil {
		fmt.Printf("创建request请求，err-->%v", err)
		return
	}
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		fmt.Printf("请求，err-->%v", err)
		return
	}
	defer response.Body.Close()
	//读取响应体的body
	res := readBody(response)
	fmt.Println(string(res))
}
func delete() {
	//Go语言未提供http.Delete方法
	request, err := http.NewRequest(http.MethodDelete, "http://httpbin.org/delete", nil)
	if err != nil {
		fmt.Printf("创建request请求，err-->%v", err)
		return
	}
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		fmt.Printf("请求，err-->%v", err)
		return
	}
	defer response.Body.Close()
	//读取响应体的body
	res := readBody(response)
	fmt.Println(string(res))
}

func main() {
	get()
	//post()
	//put()
	//delete()
	//getWithParams()
}
